package Streamer;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class Controller implements Observer
{
	private Window window;
	private Timer timer;
	private boolean clientsAreRunning = false;
	private List<TCPClient> tcpClients = new ArrayList<TCPClient>();
		
	public void go() 
	{
		window = new Window(this);
		window.setVisible(true);
	}

	@Override
	public void update(Observable o, Object observableObject) 
	{
		String message = observableObject.toString();
		
		switch (message) 
		{
			case "Timer":
				window.updateProgressbar();
				break;
	
			default:
				stopClients();
				window.displayDialog(message);
				break;
		}
		
	}
	
	public void startStop() 
	{
		
		if(!clientsAreRunning)
		{
			
			clientsAreRunning = true;
			window.toggleButtonText();
			

			for (int i = 0; i < window.getConnections(); i++) 
			{
				try 
				{
					TCPClient tcpClient = new TCPClient(window.getServerIP(), window.getServerPort());
					tcpClient.addObserver(this);
					Thread tcpClientThread = new Thread(tcpClient);
					tcpClients.add(tcpClient);
					tcpClientThread.start();
				} 
				
				catch (UnknownHostException e) 
				{
					stopClients();
					window.displayDialog("Ukendt");
					
				} 
				
				catch (IOException e) 
				{
					stopClients();
					window.displayDialog("Kan ikke forbinde til server");
					
				}
			}
			
			if (clientsAreRunning)
				startTimer();
			
			
			
		}
		
		else
		{
			stopClients();
		}
		
	}
	
	private void stopClients() 
	{
		stopTimer();
		clientsAreRunning = false;
		for (TCPClient tcpClient: tcpClients)
		{
			tcpClient.StopAll();
		}
		tcpClients.clear();
		window.toggleButtonText();
	}

	private void startTimer()
	{
		timer = new Timer(50/window.getConnections());
		timer.addObserver(this);
		Thread timerThread = new Thread(timer);
		timerThread.start();
	}
	
	private void stopTimer()
	{
		if (timer != null)
			timer.stopThread();
	}

	

}
